package com.springboot.java.design.thread;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @Author: TongRui乀
 * @Date: 2020/7/5 9:33
 * @description：
 */
@Slf4j
public class TestSemaphore {

    /**
     * 信号量
     */
    static Semaphore semaphore = new Semaphore(3);

    public static void main(String[] args) {

        ExecutorService executors = Executors.newFixedThreadPool(5);

        for (int i = 0; i < 5; i++) {
            executors.execute(new SemaphoreTask());
        }

        executors.shutdown();

    }

    static class SemaphoreTask implements Runnable{

        @Override
        public void run() {

            String threadName = Thread.currentThread().getName();

            try {
                // 获取
                semaphore.acquire();

                log.info("{}-获取到令牌", threadName);


                Thread.sleep(2000);


                log.info("{}-释放令牌", threadName);
                semaphore.release();


            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }

}
